package com.android.ailaoshan.user;

import android.content.Context;
import android.os.Message;
import android.widget.Toast;

import com.android.ailaoshan.common.BaseApplication;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.annotations.EverythingIsNonNull;


/**
 * 发送登录请求
 */
class SendRequest {

    /** 登录路径 */
    private final String LOGIN_URL = "http://192.168.1.101:8080/AilaoMIS/userLogin";

    private LoginActivity.MyHandler myHandler;
    private Context mContext;

    private String userName;
    private String userPswd;

    SendRequest(String userName, String userPswd, LoginActivity.MyHandler handler) {
        this.userName = userName;
        this.userPswd = userPswd;
        this.myHandler = handler;
        this.mContext = BaseApplication.getInstance().getbContext();
    }

    /**
     * 发送请求
     */
    void doRequest(){
        new Thread(
            ()->{
                // 发送对象构造
                FormBody.Builder builder = new FormBody.Builder();
                builder.add("userName",userName);
                builder.add("userPswd",userPswd);

                OkHttpClient httpClient = new OkHttpClient();
                RequestBody requestBody = builder.build();
                Request request = new Request.Builder()
                        .url(LOGIN_URL)
                        .post(requestBody).build();

                Call call = httpClient.newCall(request);
                call.enqueue(new ResponseHandler());
            }
        ).start();
    }

    /**
     * 内部类，处理请求结果
     */
    private class ResponseHandler implements Callback{

        @EverythingIsNonNull
        @Override
        public void onFailure(Call call, IOException e) {
            // 向服务器发送请求失败
            if(myHandler != null){
                Message msg = myHandler.obtainMessage();
                msg.what = 301;
                myHandler.sendMessage(msg);
            }else{
                Toast.makeText(mContext,"无法连接服务器...",Toast.LENGTH_LONG).show();
            }
        }

        @EverythingIsNonNull
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // 接收到服务器请求
            String responseString = response.body().string();

            if( !responseString.equals("") ){

                // JSON格式化
                Gson gson = new Gson();
                UserInfo userInfo = gson.fromJson(responseString,UserInfo.class);

                if( userInfo != null) {
                    int userId = userInfo.getUserID();

                    // 验证通过，持久化
                    if (userInfo.getLoginStatus().equals("OK")) {
                        LoginHandler loginHandler = new LoginHandler(mContext);
                        loginHandler.addData(userName, userPswd, userId);
                    }

                    if (myHandler != null) {
                        Map<String, String> responseMap = new HashMap<>();
                        responseMap.put("status", userInfo.getLoginStatus());

                        Message msg = myHandler.obtainMessage();
                        msg.what = 300;
                        msg.obj = responseMap;

                        myHandler.sendMessage(msg);
                    }
                }
            }else{
                Toast.makeText(mContext,"请求到的数据异常",Toast.LENGTH_LONG).show();
            }
        }
    }
}
